package com.zlsy.es.dianping.controller;

import com.zlsy.es.dianping.base.R;
import com.zlsy.es.dianping.baseexception.BizException;
import com.zlsy.es.dianping.constan.ErrorStatusEnum;
import com.zlsy.es.dianping.pojo.model.User;
import com.zlsy.es.dianping.service.UserService;
import com.zlsy.es.dianping.pojo.vo.request.LoginRequest;
import com.zlsy.es.dianping.pojo.vo.request.RegisterRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author zhouliang
 * @date 2020/02/29
 **/
@Slf4j
@RequestMapping("/user")
@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserController {

    private final UserService userService;
    private final HttpServletRequest httpServletRequest;
    public static final String CURRENT_USER_SESSION = "currentUserSession";

    @RequestMapping("/get")
    @ResponseBody
    public R<User> getUser(@RequestParam(name = "id") Integer id) {
        User user = userService.getId(id);
        if (Objects.isNull(user)) {
            throw new BizException(ErrorStatusEnum.NO_OBJECT_FOUND);
        }
        return R.success(user);
    }


    @RequestMapping("/register")
    @ResponseBody
    public R<User> register(@Validated @RequestBody RegisterRequest registerRequest) {

        User user = new User();
        user.setGender(registerRequest.getGender());
        user.setNickName(registerRequest.getNickName());
        user.setPassword(registerRequest.getPassword());
        user.setTelphone(registerRequest.getTelphone());

        return R.success(userService.register(user));
    }

    @RequestMapping("/login")
    @ResponseBody
    public R<User> login(@Validated @RequestBody LoginRequest loginRequest) {
        User user = userService.login(loginRequest.getPassword(), loginRequest.getTelphone());
        httpServletRequest.getSession().setAttribute(CURRENT_USER_SESSION, user);
        return R.success(user);
    }

    @RequestMapping("/logout")
    @ResponseBody
    public R logout() {
        httpServletRequest.getSession().invalidate();
        return R.success();
    }

    @RequestMapping("/getcurrentuser")
    @ResponseBody
    public R<User> getcurrentuser() {
        User user = (User) httpServletRequest.getSession().getAttribute(CURRENT_USER_SESSION);
        return R.success(user);
    }
}
